<?php

namespace App\Model;

use App\Http\Util\HomeTool;
use App\Utils\Utils;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;

class Device extends BaseModel
{
    use HasFactory, SoftDeletes;

    public $table = 'device';

    public $guarded = [];

    public $appends = ['signal_id', 'signal_num'];




    public $casts = [
        'created_at' => 'date:Y-m-d H:i:s'
    ];

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    public function offLog(){
        return $this->hasMany(DeviceOffLog::class,'device_id','id');
    }

    public function busLog(){
        return $this->hasMany(DeviceBuslog::class,'mem_device_id','id');
    }

    public function areaPrice(){
        return $this->hasMany(AreasPrice::class,'device_id','id');
    }

    public function order(){
        return $this->hasMany(Order::class,'device_id','id');
    }

    public function bus_device(){
        return $this->hasOne(DeviceBus::class,'device_id','id');
    }
    public function business()
    {
        return $this->belongsTo(Business::class);
    }

    public function agent()
    {
        return $this->belongsTo(Agent::class);
    }

    public function rate()
    {
        return $this->belongsTo(Rate::class);
    }

    public function getSignalIdAttribute()
    {
        if ($this->signal >= 20) {
            return 'height';
        }
        if ($this->signal >= 10) {
            return 'low';
        }
        if ($this->signal < 10) {
            return 'none';
        }
    }

    public function getSignalNumAttribute()
    {
        if ($this->signal > 25 && $this->signal < 99) {
            return 5;
        }
        if ($this->signal >= 21 && $this->signal <= 25) {
            return 4;
        }
        if ($this->signal >= 16 && $this->signal <= 20) {
            return 3;
        }
        if ($this->signal >= 11 && $this->signal <= 15) {
            return 2;
        }
        if ($this->signal <= 10 && $this->signal > 0) {
            return 1;
        }
        return 0;
    }

    public function makeFg(){
        $date = new \DateTime();
        $month = (int) $date->format('n');
        $list['time'] = AreasPrice::where('device_id',$this->id)
            ->where('month',$month)
            ->with('area')
            ->orderBy('season')
            ->orderBy('start')
            ->get();
        if(count($list)<=0){
            return [];
        }
        foreach($list['time'] as &$v){
            $v['count'] = HomeTool::calculateHalfHours($v['start'],$v['end']);
        }

        $list['utc'] = time();
        $list['utc']  += 8 * 3600;
        $list['coef'] = array(round($this->coef1*1000),round($this->coef2*1000),round($this->coef3*1000),round($this->coef4*1000));
        return $list;
    }

}
